package cn.edu.ecut.se2024.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.ecut.se2024.dao.SysDAO;
import cn.edu.ecut.se2024.exception.OperationFailedException;
import cn.edu.ecut.se2024.model.JSP;
import cn.edu.ecut.se2024.model.Resp;
import cn.edu.ecut.se2024.model.User;
import cn.edu.ecut.se2024.model.UserMenu;

@Service
public class SysService {

	private final SysDAO sysDAO;

	public SysService(SysDAO sysDAO) {
		this.sysDAO = sysDAO;
	}
	
	@Transactional
	public UserMenu login(String name, String pswd) {
		User user = sysDAO.login(name, pswd);
		if (user != null) {
			UserMenu userMenu = new UserMenu();
			userMenu.setUser(user);
			userMenu.setResps(sysDAO.getUserResps(user.getUserId()));
			return userMenu;
		}	else {
			return null;
		}
	}
	
	public User findUserByName(String name) {
		User user = sysDAO.findUserByName(name);
		return user;
	}
	
	public int changePassword(int userId, String oldPswd, String newPswd) throws OperationFailedException {
		int r = sysDAO.changePassword(userId, oldPswd, newPswd);
		if (r == 1) {
			return 1; 
		} else {
			throw new OperationFailedException("旧密码不正确，密码修改失败");
		}
	}
	
	@Transactional
	public int register(String userName, String nickName, String password) {
		User user = sysDAO.findUserByName(userName);
		if (user == null) {
			user = new User();
			user.setUserName(userName);
			user.setNickName(nickName);
			user.setPassword(password);
			sysDAO.insertUser(user);
			return 1;
		} else {
			return 0;
		}
	}
	
	public int deleteUser(int userId) {
		return sysDAO.deleteUser(userId);
	}
	
	public String getJspUrl(String jspCode, UserMenu userMenu) {
		if (userMenu != null) {
			for (Resp resp: userMenu.getResps()) {
				for (JSP jsp: resp.getJsps()) {
					if (jsp.getJspCode().equals(jspCode)) {
						return jsp.getJspUrl();
					}
				}
			}
		}
		return null;
	}
}
